<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
    public function authorization(Request $request)
    {
        $present_guard = Auth::getDefaultDriver();

        $request->username = 'sundy';

        $request->password = 'sundy@123';

        $token = Auth::claims(['guard' => $present_guard])->attempt(['username' => $request->username, 'password' => $request->password]);

        if ($token) {
            return $this->setStatusCode(200)->success(['token' => 'bearer ' . $token]);
        }

        return $this->failed('Incorrect user name or password', 403);
    }

    public function login(Request $request)
    {
        $present_guard = Auth::getDefaultDriver();

        $token = Auth::claims(['guard' => $present_guard])->attempt(['username' => $request->username, 'password' => $request->password]);

        if ($token) {
            return $this->respond(['status' => 'success', 'code' => 200, 'token' => 'bearer ' . $token]);
        }

        return $this->failed('Incorrect user name or password', 403);
    }

    public function ip(Request $request)
    {
        $ip = $this->getClientIp();

        return $this->success(['ip' => $ip]);
    }

    private function getClientIp()
    {
        $ip = "unknow";

        if (isset($_SERVER)) {
            if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
                $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } elseif (isset($_SERVER["HTTP_CLIENT_ip"])) {
                $ip = $_SERVER["HTTP_CLIENT_ip"];
            } else {
                $ip = $_SERVER["REMOTE_ADDR"];
            }
        } else {
            if (getenv('HTTP_X_FORWARDED_FOR')) {
                $ip = getenv('HTTP_X_FORWARDED_FOR');
            } elseif (getenv('HTTP_CLIENT_ip')) {
                $ip = getenv('HTTP_CLIENT_ip');
            } else {
                $ip = getenv('REMOTE_ADDR');
            }
        }

        if (trim($ip) == "::1") {
            $ip = "127.0.0.1";
        }

        return $ip;
    }
}
